package multiplayer.lan;

import gui.gui2d.Promotion;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Observable;

import multiplayer.lan.utility.Message;
import utility.Point;

public class TcpClient extends Observable implements Runnable , TcpObject{
	private Socket s;
	private ObjectOutputStream oos;
	ObjectInputStream ois;
	InputStream is;
	String ip="localhost";
	private int port=8457;
	
	
	public void setPort(int port) {
		this.port = port;
	}
	private boolean enable;
	public boolean isEnable() {
		return enable;
	}
	public void setEnable(boolean enable) {
		this.enable = enable;
	}
	public TcpClient(){

	}
	public void loadIp(String ip){
		String[] ipPort=ip.split(":");
		this.ip=ipPort[0];
		setPort(Integer.parseInt(ipPort[1]));
	}
	@Override
	public void sendMovement(Point from , Point to) throws IOException{
		Move m = new Move(null,from, to);
		try {
			oos.writeObject(m);
		} catch (IOException e) {
			e.printStackTrace();
			enable=false;
		}
	}
	@Override
	public void sendMessage(String nome , String message) throws IOException{
		Message inf= new Message(nome, message);
		try {
			oos.writeObject(inf);
		} catch (IOException e) {
			e.printStackTrace();
		
			enable=false;
		}
	}
	@Override
	public Object receiveObject(){

		try {
			Object o =ois.readObject();
			return  o;
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
			setChanged();
			notifyObservers(new CloseConnection("Connessione persa"));
			enable=false;
		}
		return null;
	}
	@Override
	public void connect() throws UnknownHostException, IOException  {
			enable=true;
			s= new Socket(ip,port);
			//s.setSoTimeout(10000);
			OutputStream os= s.getOutputStream();
			oos= new ObjectOutputStream(os);
			is = s.getInputStream();
			ois= new ObjectInputStream(is);
	}
	@Override
	public void run()  {

		while(enable){
			Object m = receiveObject();
			setChanged();
			notifyObservers(m);
		}

	}
	@Override
	public void sendPromotion(Promotion p) {
		try {
			oos.writeObject(p);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			enable=false;
		}
		
	}
	@Override
	public void closeConnection() {
		try {
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	@Override
	public void disable() {
		setEnable(false);
		
	}
	@Override
	public boolean isClosed() {
		return s.isClosed();
		
	}
}
